<template>
    <el-card shadow="never" class="border-0">
        <!-- 搜索 -->
        <el-form :model="searchForm" label-width="80px" class="mb-3" size="small">
            <el-row :gutter="20">
                <el-col :span="8" :offset="0">
                    <el-form-item label="角色名称">
                        <el-input v-model="searchForm.description" placeholder="角色名称" clearable></el-input>
                    </el-form-item>

                </el-col>

                <el-col :span="16">
                    <div class="flex items-center justify-end">
                        <el-button type="primary" @click="getData">搜索</el-button>
                        <el-button @click="clickResetBtn">重置</el-button>
                    </div>
                </el-col>
            </el-row>
        </el-form>


        <!-- 新增|刷新 -->
        <div class="flex items-center justify-between mb-4">
            <el-button v-if="developer" type="primary" size="small" @click="handleCreate">新增</el-button>
            <el-tooltip effect="dark" content="刷新数据" placement="top">
                <el-button text @click="getData">
                    <el-icon :size="20">
                        <Refresh />
                    </el-icon>
                </el-button>
            </el-tooltip>
        </div>

        <!-- 表格数据 -->
        <el-table :data="tableData" stripe style="width: 100%" v-loading="tableDataLoading">

            <el-table-column label="角色编码" align="center">
                <template #default="{ row }">
                    {{ row.name }}
                </template>
            </el-table-column>

            <el-table-column label="角色名称" align="center">
                <template #default="{ row }">
                    {{ row.description }}
                </template>
            </el-table-column>

            <el-table-column label="创建时间" align="center">
                <template #default="{ row }">
                    {{ dateFormatter(row.createTime) }}
                </template>
            </el-table-column>
            <el-table-column label="更新时间" align="center">
                <template #default="{ row }">
                    {{ dateFormatter(row.updateTime) }}
                </template>
            </el-table-column>
            <el-table-column label="操作" width="250" align="center">
                <template #default="scope">
                    <div>
                        <el-button v-if="developer" type="primary" size="small" text @click="clickEditBtn(scope.row)">修改</el-button>
                        <el-button type="primary" size="small" text @click="clickAuthBtn(scope.row)">权限</el-button>


                        <el-popconfirm v-if="developer" title="是否要删除该角色？" confirmButtonText="确认" cancelButtonText="取消"
                            @confirm="clickDeleteBtn(scope.row.id)">
                            <template #reference>
                                <el-button text type="primary" size="small">删除</el-button>
                            </template>
                        </el-popconfirm>
                    </div>
                </template>
            </el-table-column>
        </el-table>

        <div class="flex items-center justify-center mt-5">
            <el-pagination background layout="prev, pager ,next" :total="total" :current-page="currentPage"
                :page-size="limit" @current-change="getData" />
        </div>

        <!-- 新增 更新 抽屉 -->
        <FormDrawer ref="formDrawerRef" :title="drawerTitle" @submit="clickDrawerSubmitBtn">
            <el-form :model="form" ref="formRef" :rules="rules" label-width="80px" :inline="false">
                <el-form-item required label="角色编码" prop="name">
                    <el-input v-model="form.name" placeholder="角色编码"></el-input>
                </el-form-item>
                <el-form-item required label="角色名称" prop="description">
                    <el-input v-model="form.description" placeholder="角色名称"></el-input>
                </el-form-item>
            </el-form>
        </FormDrawer>

        <!-- 查看和更新权限 抽屉 -->
        <FormDrawer ref="formPermissionTreeRef" title="权限树" @submit="clickPermissionTreeSubmitBtn" closeBtnText="关闭" >
            <el-tree style="max-width: 300px" 
                :data="permissionTreeData" 
                show-checkbox 
                node-key="id" 
                :default-checked-keys="permissionArray"
                :props="defaultProps" 
                check-on-click-node
                :default-expand-all="true"
                ref="permissionTreeRef"
            />
        </FormDrawer>
    </el-card>

</template>

<script setup>

import { ref, onMounted, reactive, computed } from 'vue'
import { getRoleList, api_role_add, api_role_update, api_role_delete, api_role_permissions, api_role_auth_permissions } from "~/api/role";
import { api_permission_tree } from "~/api/permissionApi";
import FormDrawer from '~/components/FormDrawer.vue'
import { toast,toastWarn } from "~/composables/util"
import { dateFormatter } from '~/utils/common.js'
import { isDeveloper } from '~/utils/userInfo.js'

// 页面变量
const tableData = ref([]) // 列表数据
const currentPage = ref(1)
const total = ref(0)
const limit = ref(10)
const tableDataLoading = ref(false)
const developer = ref(false)
const rules = {
    name: [
      { required: true, message: '角色名称不能为空', trigger: 'change' }
    ],
    description: [
      { required: true, message: '角色描述不能为空', trigger: 'change' }
    ]
}
const editId = ref(0)
const drawerTitle = computed(() => editId.value ? "修改" : "新增")
const searchForm = reactive({
    description: "",
    page: currentPage.value,
    size: limit.value,
})
const form = reactive({
    id: editId.value,
    name: "",
    description: "",
})
const formRef = ref(null)
const formDrawerRef = ref(null)
const formPermissionTreeRef = ref([])
const permissionTreeRef = ref(null)
const permissionArray = ref([])
const permissionTreeData = ref([])
const defaultProps = {
  children: 'children',
  label: 'label',
}



// 生命周期
onMounted(() => {
    //判断是否是开发者账号登录
    if(isDeveloper()){
        developer.value = true
    }
    getData()
})

// 点击查看和修改权限按钮
const clickPermissionTreeSubmitBtn = () => {
    let nodes = permissionTreeRef.value.getCheckedNodes(false,true)
    if(null == nodes || nodes.length == 0){
        toastWarn("请选择权限")
        return
    }
    let ids = []
    for(let i=0;i<nodes.length;i++){
        ids.push(nodes[i].id)
    }
    console.log('req body', {
        rid: editId.value,
        ids: ids
    })

    api_role_auth_permissions({
        rid: editId.value,
        ids: ids
    }).then(res => {
        toast('修改权限成功')
        formPermissionTreeRef.value.close()
    }).catch(err => {

    })

}


// 获取权限树
const getPermissionTreeData = () => {
    api_permission_tree()
    .then(res => {
        //console.log('permission tree', res)
        permissionTreeData.value = res
    }).catch(err => {
        toast('加载权限树错误', 'error')
    })
}

// 获取角色的权限数组
const getPermissionArrByRoleId = (roleId) => {
    api_role_permissions(roleId)
    .then(res => {
        //console.log('role permission arr', res)
        permissionArray.value = res
    }).catch(err => {
        
    })
}

//获取列表数据
function getData(p = null) {
    if (typeof p == "number") {
        currentPage.value = p
    }

    tableDataLoading.value = true
    searchForm.page = currentPage.value
    getRoleList(searchForm)
        .then(res => {
            //console.log(res.records)
            if(res){
                if(!developer.value){
                tableData.value = res.records.filter(role => role.name != "developer")
                }else{
                    tableData.value = res.records
                }
                total.value = res.total
                currentPage.value = res.current
            }else{
                total.value = 0
                tableData.value = []  
            }
            // roles.value = res.roles
        })
        .finally(() => {
            tableDataLoading.value = false
        })
}

// 点击重置按钮
const clickResetBtn = () => {
    searchForm.description = ""
    getData(1)
}


// 重置表单
function resetForm(row = false) {
    if (formRef.value) formRef.value.resetFields()
    if (row) {
        for (const key in form) {
            form[key] = row[key]
        }
    }
}

// 新增
const handleCreate = () => {
    //修改标记置为0
    editId.value = 0
    resetForm()
    formDrawerRef.value.open()
}

// 点击新增角色抽屉中 提交按钮
const clickDrawerSubmitBtn = () => {
    formRef.value.validate((valid) => {
        if (!valid) return

        formDrawerRef.value.showLoading()

        const fun = editId.value ? api_role_update(editId.value, form) : api_role_add(form)

        fun.then(res => {
            toast(drawerTitle.value + "成功")
            // 修改刷新当前页，新增刷新第一页
            getData(editId.value ? false : 1)
            formDrawerRef.value.close()
        }).finally(() => {
                formDrawerRef.value.hideLoading()
            })

    })
}

// 编辑
const clickEditBtn = (row) => {
    editId.value = row.id
    resetForm(row)
    formDrawerRef.value.open()
}

// 查看和编辑权限
const clickAuthBtn = (row) => {
    //清空已选数据
    permissionArray.value = []
    //权限树弹窗
    editId.value = row.id
    formPermissionTreeRef.value.open()

    //加载权限树以及当前角色权限
    initTree(row.id)
}

//加载顺序
const initTree = async(roleId) => {
    //加载权限树
    await api_permission_tree()
    .then(res => {
        //console.log('permission tree', res)
        permissionTreeData.value = res
    }).catch(err => {
        toast('加载权限树错误', 'error')
    })
    //获取当前角色权限
    await api_role_permissions(roleId)
    .then(res => {
        //console.log('role permission arr', res)
        permissionArray.value = res
    }).catch(err => {
        toast('加载权限树错误', 'error')
    })
}

// 删除
const clickDeleteBtn = (id) => {
    tableDataLoading.value = true
    api_role_delete(id).then(res => {
        toast("删除成功")
        getData()
    }).catch(err => {

    }).finally(() => {
        tableDataLoading.value = false
    })
}

</script>